package com.cimr.service.manager.impl;
import com.cimr.comm.base.BaseDao;
import com.cimr.comm.base.BaseServiceImpl;
import com.cimr.comm.po.User;
import com.cimr.comm.service.UserService;
import com.cimr.comm.token.TokenUtil;
import com.cimr.comm.util.IdUtil;
import com.cimr.dao.manager.UserInfoDao;
import com.cimr.dto.manager.UserInfoDto;
import com.cimr.dto.file.FileDto;
import com.cimr.po.file.UnitFile;
import com.cimr.po.manager.UserInfo;
import com.cimr.service.manager.UserInfoService;
import com.cimr.service.file.UnitFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by suhuanzhao on 2017/12/25.
 */
@Service
public class UserInfoServiceImpl extends BaseServiceImpl<UserInfo> implements UserInfoService{

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private UnitFileService unitFileService;

    @Autowired
    private UserService userService;

    @Override
    protected BaseDao getDao() {
        return userInfoDao;
    }

    @Override
    public List<UserInfo> getList(String username,String fullname,String phone,String email,Float orderId,String theme,
                                  String nickName, String realName, String userType, String province, String city, String area,
                                  String address, String sex, String orgId, String userId, String idCard,
                                  String flag ) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setFullname(fullname);
        userInfo.setPhone(phone);
        userInfo.setEmail(email);
        userInfo.setOrderId(orderId);
        userInfo.setTheme(theme);
        userInfo.setNickName(nickName);
        userInfo.setRealName(realName);
        userInfo.setUserType(userType);
        userInfo.setProvince(province);
        userInfo.setCity(city);
        userInfo.setArea(area);
        userInfo.setAddress(address);
        userInfo.setSex(sex);
        userInfo.setOrgId(orgId);
        userInfo.setUserId(userId);
        userInfo.setIdCard(idCard);
        userInfo.setFlag(flag);
        return userInfoDao.selectList(userInfo);
    }

    @Override
    public String deleteByArray(String[] ids) {
        userInfoDao.deleteByArray(ids);
        return "删除成功";
    }

    @Override
    public String insert(String username,String pswd,String fullname,String phone,String email,String comment,Float orderId, String theme,
                       String nickName, String realName, String userType, String province, String city, String area,
                       String address, String sex, String orgId, String userId, String idCard,
                       String remarks, String flag,String fileJson,String realPath) {

        //账号唯一性检查
        if(username == null || "".equals(username)){
            return "添加失败，用户名不能为空";
        }
        User u = userService.getByUsername(username);

        //上传头像
        List<UnitFile> files = unitFileService.uploadFiles(fileJson,realPath,userId,null,null,userId);
        String headImgId = null;
        //保存头像图片的文件ID
        if(files != null && !files.isEmpty()){
            headImgId = files.get(0).getId();
        }
        //新增user对象
        if (userId == null || "".equals(userId)) {
            userId = IdUtil.getId().toString();
            userService.insertUser(userId, username,
                    pswd, 1, fullname, phone, email,
                    comment,orderId, null, null, theme,headImgId);
        } else {
            //先删除以前的图片
            User u1 = userService.getUserById(userId);
            unitFileService.deleteFile(u1.getAvatar(), u1.getId());

            if(!u1.getUsername().equals(u.getUsername())){
                if (u != null) {
                    return "该账号已经存在！";
                }
            }

            //更新user对象
            userService.updateUser(userId, username,
                    null, 1, fullname,phone, email,
                    comment, orderId, null, null, theme ,headImgId);
        }
        //新增userInfo对象
        String id = IdUtil.getId().toString();
        UserInfo userInfo = new UserInfo(id, nickName,  realName,  userType,  province,  city,  area,
                 address,  sex,  null,  orgId,  userId,  idCard,  null,  null,
                 remarks,  flag,  TokenUtil.getUserId(),  new Date(),  TokenUtil.getUserId(),  new Date());

//        //上传头像
//        List<UnitFile> files = unitFileService.uploadFiles(fileJson,realPath,userInfo.getId(),null,null,userInfo.getUserId());
//
//        //保存头像图片的文件ID
//        if(files != null && !files.isEmpty()){
//            userInfo.setHeadImgId(files.get(0).getId());
//        }
        this.insertObject_common(userInfo);
        return "添加成功";
    }

    @Override
    public String update(String id,String username,String pswd,String fullname,String phone,String email,String comment,Float orderId,String theme,
                       String nickName, String realName, String userType, String province, String city, String area,
                       String address, String sex, String orgId, String userId, String idCard,
                       String remarks, String flag ,String fileJson,String realPath) {
        User u1 = userService.getUserById(userId);
        if(u1 == null){
            return "更新失败，不存在该用户";
        }
        //账号唯一性检查
        if(username == null || "".equals(username)){
            return "添加失败，用户名不能为空";
        }
        User u = userService.getByUsername(username);
        if(!username.equals(u.getUsername())){
            if (u != null) {
                return "该账号已经存在！";
            }
        }
        //上传头像
        List<UnitFile> files = unitFileService.uploadFiles(fileJson,realPath,userId,null,null,userId);
        String headImgId = null;
        //保存头像图片的文件ID
        if(files != null && !files.isEmpty()){
            headImgId = files.get(0).getId();
        }
        UserInfo userInfo1 = this.selectById_common(id);
        //更新user对象
        userService.updateUser(userId, username,
                null, 1, fullname, phone, email,
                comment, orderId, null, null, theme, headImgId);
        //更新userInfo对象
        UserInfo userInfo = new UserInfo(id, nickName,  realName,  userType,  province,  city,  area,
                address,  sex,  null,  orgId,  userId,  idCard,  null,  null,
                remarks,  flag,  null,  null,  TokenUtil.getUserId(),  new Date());
//        if(fileJson != null && !"".equals(fileJson)
//                && !"[]".equals(fileJson)){
//            //更新图片之前，先删除旧图片
//            unitFileService.deleteFile(userInfo1.getHeadImgId(), userInfo.getUserId());
//            //重新上传新的图片
//            //上传头像
//            List<UnitFile> files = unitFileService.uploadFiles(fileJson,realPath,userInfo.getId(),null,null,userInfo.getUserId());
//
//            //保存头像图片的文件ID
//            if(files != null && !files.isEmpty()){
//                userInfo.setHeadImgId(files.get(0).getId());
//            }
//        }
        this.updateObject_common(userInfo);
        return "更新成功";
    }

    @Override
    public String delete(String userId) {
//        UserInfo ui = this.selectById_common(userInfoId);
        User user = userService.getUserById(userId);
        if(user == null){
            return "删除失败，不存在该用户!";
        }
        UserInfo ui = this.getByUserId(userId);
        //删除user对象
        userService.deleteUser(userId);

        //删除userInfo对象以及相关的文件和图片
        if(ui != null){
            //删除头像
            if (ui.getHeadImgId() != null && !"".equals(ui.getHeadImgId())) {
                unitFileService.deleteFile(ui.getHeadImgId(), userId);
            }
            //删除附件
            if (ui.getAttachId() != null && !"".equals(ui.getAttachId())) {
                unitFileService.deleteFile(ui.getAttachId(), userId);
            }
            //删除userInfo对象
            this.deleteById_common(ui.getId());
        }
        return "删除成功";
    }

    @Override
    public UserInfo getByUserId(String userId) {
        return userInfoDao.selectByUserId(userId);
    }

    @Override
    public String insertByObj(UserInfoDto userInfoDto) {

        //账号唯一性检查
        if(userInfoDto.getUsername() == null || "".equals(userInfoDto.getUsername())){
            return "添加失败，用户名不能为空";
        }

        //上传头像
        List<UnitFile> files = unitFileService.uploadFiles(userInfoDto.getFileJson(),userInfoDto.getRealPath(),userInfoDto.getUserId(),null,null,userInfoDto.getUserId());
        String headImgId = null;
        //保存头像图片的文件ID
        if(files != null && !files.isEmpty()){
            headImgId = files.get(0).getId();
        }
        User u = userService.getByUsername(userInfoDto.getUsername());
        //新增user对象
        if (userInfoDto.getUserId() == null || "".equals(userInfoDto.getUserId())) {
            String userId = IdUtil.getId().toString();
            userInfoDto.setUserId(userId);
            userService.insertUser(userId, userInfoDto.getUsername(),
                    userInfoDto.getPswd(), 1, userInfoDto.getFullname(), userInfoDto.getPhone(), userInfoDto.getEmail(),
                    userInfoDto.getComment(), userInfoDto.getOrderId(), null,null,userInfoDto.getTheme(),headImgId);
        } else {
            //更新user对象
            User u1 = userService.getUserById(userInfoDto.getUserId());
            if(!u1.getUsername().equals(u.getUsername())){
                if (u != null) {
                    return "该账号已经存在！";
                }
            }
            //先删除以前的图片
            unitFileService.deleteFile(u1.getAvatar(), u1.getId());
            userService.updateUser(userInfoDto.getUserId(), userInfoDto.getUsername(),
                    userInfoDto.getPswd(), 1, userInfoDto.getFullname(), userInfoDto.getPhone(), userInfoDto.getEmail(),
                    userInfoDto.getComment(), userInfoDto.getOrderId(), null, null, userInfoDto.getTheme(), headImgId);
        }
        //新增userInfo对象
        UserInfo userInfo = new UserInfo(userInfoDto);
        userInfo.setId(IdUtil.getId().toString());
        userInfo.setCreateTime(new Date());
        userInfo.setCreateBy(TokenUtil.getUserId());
        userInfo.setUpdateTime(new Date());
        userInfo.setUpdateBy(TokenUtil.getUserId());

//        //上传头像
//        List<UnitFile> files = unitFileService.uploadFiles(userInfoDto.getFileJson(),userInfoDto.getRealPath(),userInfo.getId(),null,null,userInfo.getUserId());
//
//        //保存头像图片的文件ID
//        if(files != null && !files.isEmpty()){
//            userInfo.setHeadImgId(files.get(0).getId());
//        }
        this.insertObject_common(userInfo);
        return "添加成功";
    }

    @Override
    public String updateByObj(UserInfoDto userInfoDto) {
        User u1 = userService.getUserById(userInfoDto.getUserId());
        if(u1 == null){
            return "更新失败，不存在该用户";
        }
        //上传头像
        List<UnitFile> files = unitFileService.uploadFiles(userInfoDto.getFileJson(),userInfoDto.getRealPath(),userInfoDto.getUserId(),null,null,userInfoDto.getUserId());
        String headImgId = null;
        //保存头像图片的文件ID
        if(files != null && !files.isEmpty()){
            headImgId = files.get(0).getId();
        }
        //先删除以前的图片
        unitFileService.deleteFile(u1.getAvatar(), u1.getId());
        //更新user对象
        userService.updateUser(userInfoDto.getUserId(), userInfoDto.getUsername(),
                null, 1, userInfoDto.getFullname(), userInfoDto.getPhone(), userInfoDto.getEmail(),
                userInfoDto.getComment(), userInfoDto.getOrderId(), null, null, userInfoDto.getTheme(), headImgId);
        //账号唯一性检查
        if(userInfoDto.getUsername() == null || "".equals(userInfoDto.getUsername())){
            return "添加失败，用户名不能为空";
        }
        User u = userService.getByUsername(userInfoDto.getUsername());
        if(!u1.getUsername().equals(u.getUsername())){
            if (u != null) {
                return "该账号已经存在！";
            }
        }
        //更新userInfo对象
        UserInfo userInfo = new UserInfo(userInfoDto);
        userInfo.setUpdateTime(new Date());
        userInfo.setUpdateBy(TokenUtil.getUserId());

//        UserInfo userInfo1 = this.selectById_common(userInfo.getId());


//        if(userInfoDto.getFileJson() != null && !"".equals(userInfoDto.getFileJson())
//                && !"[]".equals(userInfoDto.getFileJson())){
//            //更新图片之前，先删除旧图片
//            unitFileService.deleteFile(userInfo1.getHeadImgId(), userInfo.getUserId());
//            //重新上传新的图片
//            //上传头像
//            List<UnitFile> files = unitFileService.uploadFiles(userInfoDto.getFileJson(),userInfoDto.getRealPath(),userInfo.getId(),null,null,userInfo.getUserId());
//
//            //保存头像图片的文件ID
//            if(files != null && !files.isEmpty()){
//                userInfo.setHeadImgId(files.get(0).getId());
//            }
//
//        }
        this.updateObject_common(userInfo);
        return "更新成功";
    }
}
